﻿using System.Collections.ObjectModel;
using System.Windows.Input;
using MediaMover.Common.TV;
using MediaMover.Data;
using MediaMover.MVVM.Commands;
using Ninject;

namespace MediaMover.MVVM.ViewModels
{
    public class ScanViewModel : WorkspaceViewModel
    {
        private IKernel _kernel;
        private Access _dbAccess;
        public ScanViewModel(IKernel kernel)
        {
            DisplayName = "Scan";
            _kernel = kernel;
            _dbAccess = _kernel.Get<Access>();
            _shows = new ObservableCollection<Show>(_dbAccess.ShowRepository.GetShows());
        }
             
        private ObservableCollection<Show> _shows { get; set; }
        private ObservableCollection<Episode> _missingEpisodes = new ObservableCollection<Episode>();
        public ObservableCollection<Episode> MissingEpisodes
        {
            get { return _missingEpisodes; }
            set { _missingEpisodes = value; }
        }

        public ObservableCollection<Episode> RenameEpisodes { get; set; }
        public ObservableCollection<Episode> MoveEpisodes { get; set; }

        public string EpisodeNameFormat { get; set; }
        private ICommand _scanCommand;
        public ICommand ScanCommand
        {
            get
            {
                if (_scanCommand == null)
                {
                    _scanCommand = new RelayCommand(param => Scan(), 
                                                    param => CanScan());
                }
                return _scanCommand;
            }
            set { _scanCommand = value; }
        }

        private bool CanScan()
        {
            return IsScanning == false;
        }

        private bool IsScanning { get; set; }
        public void Scan()
        {
            IsScanning = true;
            foreach (var show in _shows)
            {
                show.Update();
                foreach (var season in show.Seasons)
                {
                    foreach (var episode in season.Episodes)
                    {
                        if (episode.IsMissing())
                        {
                            MissingEpisodes.Add(episode);
                            continue;
                        }
                        if (episode.NeedsMove() && episode.NeedsRename())
                        {
                            MoveEpisodes.Add(episode);
                        }
                        else if (episode.NeedsRename())
                        {
                            RenameEpisodes.Add(episode);
                        }
                    }
                }
            }
            IsScanning = false;
        }
    }
}
